import React, { useState, useEffect, useMemo } from 'react';
import { connect } from 'umi';
import {
  Table,
  Button,
  Modal,
  Form,
  Row,
  Col,
  Select,
  Input,
  message,
  notification,
} from 'antd';
import { selectOption } from './SettingGlobal';
import { deviceTypeList, sensorUpdate, sensorAdd } from './setServers';

const { Option } = Select;
const startType = [
  { name: '是', value: 'Y' },
  { name: '否', value: 'N' },
];

/* 编辑 */
const EditAddModal = (props: any) => {
  const [modalForm] = Form.useForm();

  const {
    modalVisible,
    modalDatas,
    sensorTypeListAll,
    editModalOk,
    closeVisible,
  } = props;

  // console.log('Form 表单数据', modalDatas);

  useEffect(() => {
    if (!modalDatas) {
      modalForm.resetFields();
    } else {
      modalForm.setFieldsValue(modalDatas);
    }
  }, []);

  const modalOnOk = async () => {
    if (modalDatas['MY__TYPE'] === 'ADD') {
      modalForm.validateFields().then((res) => {
        // console.log('modal 添加数据', res);
        sensorAdd(res).then((res) => {
          // console.log('添加是否成功', res);
          notification.success({
            message: '添加结果！',
            description: res.message || '添加成功！',
          });
          editModalOk();
        });
      });
    } else {
      modalForm.validateFields().then((res) => {
        // console.log('获取 表单 数据', res, modalDatas['id']);
        sensorUpdate({ ...res, id: modalDatas['id'] })
          .then((res) => {
            notification.success({
              message: '修改结果！',
              description: res.message || '修改成功！',
            });
            editModalOk();
          })
          .catch((rej) => {
            notification.error({
              message: '修改结果！',
              description: rej.message || '修改失败！',
            });
          });
      });
    }
  };

  return (
    <Modal
      title={modalDatas['MY__TYPE'] === 'ADD' ? modalDatas['title'] : '编辑'}
      maskClosable={false}
      visible={modalVisible}
      width={800}
      onOk={modalOnOk}
      onCancel={() => {
        closeVisible();
      }}
    >
      <Form
        form={modalForm}
        name="modalForm"
        labelCol={{ span: 8 }}
        autoCapitalize="off"
        autoComplete="off"
        // initialValues={{
        //   ...modalDatas
        // }}
      >
        <Row gutter={24} align="middle">
          <Col span={12}>
            <Form.Item label="感测器类别" name="type">
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="感测器类别名称" name="typename">
              <Input />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="分类" name="sensortype">
              <Select>
                {selectOption(sensorTypeListAll, 'CODE', 'REMARK')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="启用（页面显示）" name="isactive">
              <Select>{selectOption(startType, 'value', 'name')}</Select>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

const SensorTypeSet = (props: any) => {
  const { history } = props;
  const { dvaData } = props;
  // console.log('获取 感测器类被设定的 dva 数据', dvaData, props);
  const [dataSource, setDataSource] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalDatas, setModalDatas] = useState({});

  const getTableData = () => {
    deviceTypeList().then((res) => {
      console.log('感测器类别设定 数据请求', res);
      res['data'] && setDataSource(res['data']);
    });
  };
  const closeVisible = () => {
    setModalVisible(false);
  };

  useEffect(() => {
    // getTableData()
    setDataSource(dvaData['deviceTypeListAll']);
  }, []);

  const editModalOk = () => {
    getTableData();
    // 更新dva中的全局数据
    props.onSetDeviceType();
    setModalVisible(false);
  };

  const columns = [
    { title: '感测器类别', dataIndex: 'type', key: 'type' },
    { title: '感测器类别名称', dataIndex: 'typename', key: 'typename' },
    {
      title: '分类',
      dataIndex: 'sensortype',
      key: 'sensortype',
      render: (text: string) => {
        for (const item of dvaData['sensorTypeListAll']) {
          if (item['CODE'] === text) {
            return item['REMARK'];
          }
        }
      },
    },
    { title: '启用', dataIndex: 'isactive', key: 'isactive' },
    {
      title: '处理',
      dataIndex: '',
      render: (record: any) => {
        return (
          <div>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                // console.log(record, 'record');
                setModalDatas(record);
                setModalVisible(true);
              }}
            >
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() => {
                // console.log('路由跳转', record);
                record['id']
                  ? history.push(`/SensorItemMtn/${record['id']}`, record)
                  : message.error('缺少ID');
              }}
            >
              编辑感测项目
            </Button>
          </div>
        );
      },
    },
  ];

  const editAddModal = useMemo(() => {
    return (
      <EditAddModal
        modalVisible={modalVisible}
        modalDatas={modalDatas}
        sensorTypeListAll={dvaData['sensorTypeListAll']}
        editModalOk={editModalOk}
        closeVisible={closeVisible}
      />
    );
  }, [modalVisible]);

  return (
    <>
      <Row gutter={24}>
        <Col span={22}>
          <h2>感測器類別設定</h2>
        </Col>
        <Col span={2}>
          <Button
            type="primary"
            onClick={() => {
              setModalDatas({ MY__TYPE: 'ADD', title: '添加' });
              setModalVisible(true);
            }}
          >
            添加
          </Button>
        </Col>
      </Row>
      <Table
        rowKey={(record: any): string =>
          record['id'] || Math.random().toString(16)
        }
        size="small"
        columns={columns}
        dataSource={dataSource}
        pagination={false}
      />
      {modalVisible && editAddModal}
    </>
  );
};

/* 挂载 到仓库中 */
const mapStateToProps = (state: any) => ({
  // dvaData 属性名称 setting 指命名空间
  dvaData: state.setting,
});
/* 更新dva全局数据 */
const mapDispathToProps = (dispatch: any) => {
  // console.log('dva dispatch 触发', dispatch);
  // dispath 分发
  return {
    onSetDeviceType() {
      dispatch({ type: 'setting/getDeviceTypeAll' });
    },
  };
};

export default connect(mapStateToProps, mapDispathToProps)(SensorTypeSet);
